const Service = require("egg").Service;
const NotFoundException = require("../exception/not_found");
const { Op } = require("sequelize");

Date.prototype.Format = function (fmt) {
  const o = {
    "M+": this.getMonth() + 1, // 月份
    "d+": this.getDate(), // 日
    "H+": this.getHours(), // 小时
    "m+": this.getMinutes(), // 分
    "s+": this.getSeconds(), // 秒
    "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
    S: this.getMilliseconds(), // 毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (const k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return fmt;
};

class UsersService extends Service {
  // 登录获取用户信息
  async findByLogin(openid) {
    const { ctx } = this;
    let userId = {};
    userId = await ctx.model.User.findByLogin(openid);
    return userId;
  }

  // 用户管理创建用户列表
  async createUser(params) {
    const { ctx } = this;
    try {
      const { nickname, openid, avatar_url } = params;
      const user = await ctx.model.User.create({
        nickname,
        openid,
        avatar_url,
      });
      return user;
    } catch (error) {
      console.log("------看看error-------", error);
      console.log("------end-------");
      throw new NotFoundException("新增失败", 500);
    }
  }
  async updateUserInfo(id, name, js_number, avatar, role, classList) {
    const { ctx } = this;
    try {
      const result = await ctx.model.transaction(async (t) => {
        const user = await ctx.model.User.findOne(
          {
            where: {
              id,
            },
          },
          { transaction: t }
        );

        const roles = await ctx.model.Role.findAll(
          {
            where: {
              role_id: {
                [Op.in]: role,
              },
            },
          },
          { transaction: t }
        );
        await user.setRole(roles, { transaction: t });
        const classes = await ctx.model.Class.findAll(
          {
            where: {
              class_id: {
                [Op.in]: classList,
              },
            },
          },
          { transaction: t }
        );
        if (classes) {
          await user.setClass(classes, { transaction: t });
        }
        const updated_at = new Date().Format("yyyy-MM-dd HH:mm:ss");
        await user.update(
          {
            name,
            js_number,
            // avatar, // 暂时不更新
            updated_at,
          },
          { transaction: t }
        );
      });
      return result;
    } catch (error) {
      console.log("------看看error-------", error);
      console.log("------end-------");
      throw new NotFoundException("编辑失败", 500);
    }
  }

  async destroy(id) {
    const { ctx } = this;
    try {
      const result = await ctx.model.transaction(async (t) => {
        const user = await ctx.model.User.destroy(
          { where: { id } },
          { transaction: t }
        );
        await ctx.model.UserRole.destroy(
          { where: { user_id: id } },
          { transaction: t }
        );
        return user;
      });
      return result;
    } catch (error) {
      throw new NotFoundException("删除失败", 500);
    }
  }
}

module.exports = UsersService;
